package tt.dz.egobus.servicemanager.core.interceptor;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.WebUtils;
import tt.dz.egobus.servicemanager.bean.UserSession;
import tt.dz.egobus.servicemanager.core.filter.CorsEnable;
import tt.dz.egobus.servicemanager.core.filter.FileExistCorsEnable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Anson
 * @date 17-4-20
 * @name json timeout 的处理
 * @since 1.0.4
 */
public class JsonSessionHandlerInterceptor extends SessionInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonSessionHandlerInterceptor.class);

    private static final String JSON_TIME_OUT_RESPONSE = "sessionTimeout";
    private static final String JSON_HEAD_KEY = "X-Requested-With";

    private static final String[] FILTER_URLS = {"/index.html"};
    private final CorsEnable corsEnable = new FileExistCorsEnable();

    @Override
    protected boolean isFilter(HttpServletRequest request) {
        boolean isFilter = false;
        boolean isAjax = false;
        String requestType = request.getHeader(JSON_HEAD_KEY);
        isAjax = requestType != null;
        if (!isAjax) {
            String url = request.getRequestURI();
            url = url.substring(url.lastIndexOf("/"));
            isFilter = ArrayUtils.contains(FILTER_URLS, url);
        } else {
            isFilter = isAjax;
        }
        if (corsEnable.isEnable()) {
            //当前若存在跨域处理
            isFilter = false;
        }
        return isFilter;
    }

    @Override
    protected boolean successSessionValidate(UserSession userSession, HttpServletRequest request, HttpServletResponse
            response, Object handler) {
        if (userSession == null) {
            return false;
        }
        userSession.updateSession();
        WebUtils.setSessionAttribute(request, ADMIN_SESSION_KEY, userSession.toJson());
        return true;
    }

    @Override
    protected boolean invalidateSessionValidate(UserSession userSession, HttpServletRequest request,
                                                HttpServletResponse response, Object handler) {
        LOGGER.info("当前用户session未通过,处理当前用户登陆session为null");
        WebUtils.setSessionAttribute(request, ADMIN_SESSION_KEY, null);
        PrintWriter write = null;
        try {
            write = response.getWriter();
            write.write(JSON_TIME_OUT_RESPONSE);
        } catch (IOException e) {
            LOGGER.error("当前用户session超时,获取response中PrintWriter异常", e);
        } finally {
            if (write == null) {
                write.close();
            }
        }
        return false;
    }
}